<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班车" prop="busId">
        <el-select v-model="queryParams.busId" placeholder="请选择班车" clearable style="width: 240px">
          <el-option
            v-for="item in busList"
            :key="item.id"
            :label="`${item.licensePlate} (${item.maxCapacity}人)`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="司机" prop="driverId">
        <el-input
          v-model="queryParams.driverId"
          placeholder="请输入关联 user.id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="往返线路" prop="line">
        <el-select v-model="queryParams.line" placeholder="请选择往返线路" clearable style="width: 240px">
          <el-option
            v-for="dict in lineOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择计划状态" clearable style="width: 100px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:schedule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:schedule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:schedule:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:schedule:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="班车" align="center" prop="busId">
        <template #default="scope">
          <span>{{ busList.find(bus => bus.id === scope.row.busId)?.licensePlate + ' (荷载: ' + busList.find(bus => bus.id === scope.row.busId)?.maxCapacity + '人)' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="司机" align="center" prop="driverId">
        <template #default="scope">
          <span>{{ userList.find(user => user.userId === String(scope.row.driverId))?.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发车安排" align="center" prop="departureDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.week ? scope.row.week : parseTime(scope.row.departureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="往返线路" align="center" prop="line">
        <template #default="scope">
          <span>{{ lineOptions.find(item => item.value == scope.row.line)?.label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ statusOptions.find(item => item.value === scope.row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:schedule:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:schedule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存储每日发车安排对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="scheduleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班车" prop="busId">
          <el-select v-model="form.busId" placeholder="请选择班车">
            <el-option
              v-for="bus in busList"
              :key="bus.id"
              :label="bus.licensePlate + ' (荷载: ' + bus.maxCapacity + '人)'"
              :value="bus.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发车模式" prop="scheduleMode">
          <el-radio-group v-model="scheduleMode">
            <el-radio label="date">按日期</el-radio>
            <el-radio label="week">按周循环</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发车日期" prop="departureDate" v-if="scheduleMode === 'date'">
          <el-date-picker clearable
            v-model="form.departureDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发车日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作日" prop="week" v-if="scheduleMode === 'week'">
          <el-checkbox-group v-model="week">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="7">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="司机" prop="driverId">
          <el-select v-model="form.driverId" placeholder="请选择司机">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="往返线路" prop="line">
          <el-select v-model="form.line" placeholder="请选择往返线路">
            <el-option
              v-for="dict in lineOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="计划状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择计划状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedule">
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule } from "@/api/busmanagement/schedule";
import { listBus } from "@/api/busmanagement/bus"; // 导入班车管理API
import { listUser } from "@/api/system/user"; // 导入用户管理API

const { proxy } = getCurrentInstance();

const scheduleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const scheduleMode = ref('date'); // 'date' or 'week'
const week = ref([]);
const tempDate = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    busId: null,
    driverId: null,
    departureDate: null,
    departureTime: null,
    line: null,
    currentCount: null,
    maxCapacity: null,
    status: null, // 默认计划状态为正常
    createTime: null,
    updateTime: null,
    week: null,
  },
  rules: {
    busId: [
      { required: true, message: "关联 t_bus.id不能为空", trigger: "blur" }
    ],
    driverId: [
      { required: true, message: "司机不能为空", trigger: "change" }
    ],
    departureDate: [
      { required: () => scheduleMode.value === 'date', message: "发车日期不能为空", trigger: "blur" }
    ],
    line: [
      { required: true, message: "往返线路不能为空", trigger: "blur" }
    ],
    currentCount: [
      { required: true, message: "当前预约人数不能为空", trigger: "blur" }
    ],
    maxCapacity: [
      { required: true, message: "本次发车核载人数不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "计划状态不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const busList = ref([]); // 班车列表
const userList = ref([]); // 用户列表
// 往返线路选项
const lineOptions = ref([
  { value: 1, label: '上午-青州---潍坊' },
  { value: 2, label: '下午-青州---潍坊' },
  { value: 3, label: '上午-潍坊---青州' },
  { value: 4, label: '下午-潍坊---青州' },
]);

// 计划状态选项
const statusOptions = ref([
  { value: 1, label: '正常' },
  { value: 2, label: '停用' },
]);

/** 查询班车列表 */
function getBusList() {
  listBus().then(response => {
    busList.value = response.rows;
  });
}

/** 查询用户列表 */
function getUserList() {
  listUser({ deptId: 210 }).then(response => {
    userList.value = response.rows;

  });
}

/** 查询存储每日发车安排列表 */
function getList() {
  loading.value = true;
  listSchedule(queryParams.value).then(response => {
    scheduleList.value = response.rows;
    total.value = response.total;
    loading.value = false;

  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    busId: null,
    driverId: null,
    departureDate: null,
    departureTime: null,
    line: null,
    currentCount: null,
    maxCapacity: null,
    status: null,
    createTime: null,
    updateTime: null,
    week: null,
  };
  proxy.resetForm("scheduleRef");
  scheduleMode.value = 'date';
  week.value = [];
  tempDate.value = null;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储每日发车安排";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSchedule(_id).then(response => {
    form.value = response.data;
    if (form.value.driverId) {
      form.value.driverId = String(form.value.driverId);
    }
    // 根据后端数据自动切换发车模式并还原选项
    if (form.value.week) {
      scheduleMode.value = 'week';
      week.value = form.value.week.split(','); // 将周字符串转换为数组
    } else if (form.value.departureDate) {
      scheduleMode.value = 'date';
    }
    open.value = true;
    title.value = "修改存储每日发车安排";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scheduleRef"].validate(valid => {
    if (valid) {
      const data = { ...form.value };
      if (scheduleMode.value === 'week') {
        data.week = week.value.join(',');
        data.departureDate = null; // 在周循环模式下，日期字段应为空
      } else {
        data.week = null; // 在按日期模式下，周循环字段应为空
      }

      if (data.id != null) {
        updateSchedule(data).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchedule(data).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除存储每日发车安排编号为"' + _ids + '"的数据项？').then(function() {
    return delSchedule(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schedule/schedule/export', {
    ...queryParams.value
  }, `schedule_${new Date().getTime()}.xlsx`)
}

getList();
getBusList(); // 获取班车列表
getUserList(); // 获取用户列表
</script>
